<script lang='ts' setup>
import { watchEffect } from 'vue'
import { Delete } from "@element-plus/icons-vue";
import { IFormItem } from "../../../type";

interface IProps {
  item: IFormItem
}
interface IEmit {
  (event: "update:item", data: any): void
  (event: "fixData", data: any): void
}
const props = defineProps<IProps>()
const emit = defineEmits<IEmit>()

function handleAdd() {
  const length = props.item.options.length ?? 0
  const index = length + 1
  props.item.options.push({ index: index, show: true, label: `选项${index}`, value: index })
}

function handleRemove(index: number) {
  props.item.options.splice(index, 1)
}

function resetDefault() {
  props.item.defaultValue = undefined
}
watchEffect(() => {
  if (props.item.selectMulti) {
    props.item.defaultValue = []
  } else {
    props.item.defaultValue = undefined
  }
})
</script>

<template>
  <el-row>
    <el-col :span="8">
      <el-form-item label="是否多选">
        <el-switch v-model="item.selectMulti" :active-value="true" :inactive-value="false" />
      </el-form-item>
    </el-col>
    <el-col :span="12">
      <el-form-item label="选项宽度">
        <el-input-number v-model="item.optionWidth" :step="10" :controls="true" />
      </el-form-item>
    </el-col>
  </el-row>

  <el-form-item label="选项设置">
    <!-- 不多选 -->
    <el-radio-group v-if="!item.selectMulti" v-model="item.defaultValue" style="width: 400px;">
      <el-radio v-for="(option, index) in item.options" :key="index" :label="option.value">
        <el-input v-model="option.value" placeholder="请输入选项key" style="width: 100px;" />
        <el-input v-model="option.label" placeholder="请输入选项标签" style="width: 100px;" />
        <el-button @click="handleRemove(index)" size="small" item.type="danger" text :icon="Delete"></el-button>
        <el-switch v-model="option.show" />
      </el-radio>
    </el-radio-group>
    <!-- 多选框 -->
    <el-checkbox-group v-else v-model="item.defaultValue">
      <el-checkbox v-for="(option, index) in item.options" :key="index" :label="option.value">
        <el-input v-model="option.value" style="width: 100px;" />
        <el-input v-model="option.label" style="width: 100px;" />
        <el-button @click="handleRemove(index)" size="small" item.type="danger" text :icon="Delete"></el-button>
        <el-switch v-model="option.show" />
      </el-checkbox>
    </el-checkbox-group>
    <!--  增加选项  -->
    <el-row style="margin-top: 1rem;width: 100%;">
      <el-button text type="success" size="small" @click="handleAdd">增加选项
      </el-button>
      <el-button text size="small" type="warning" @click="resetDefault">重置默认值</el-button>
    </el-row>
  </el-form-item>

  <el-form-item label="占位字符" prop="placeholder">
    <el-input v-model="item.placeholder" placeholder="未填入数据时显示的内容" :maxLength="20" clearable></el-input>
  </el-form-item>
</template>

<style lang='scss' scoped></style>